import { Collider2D, Node, math, sp, v2 } from "cc";
import { BaseCharacter } from "./BaseCharacter";

/*****************************
 *@file: GameUtils
 *@author: 陈吕唐
 *@desc: 游戏工具类
 *@date: 2024-03-18	15:19
 *****************************/
export default class GameUtils {

    /**
     * 通过碰撞器获取角色
     * @param collider
     */
    public static getCharacterByCollider(collider: Collider2D) {
        if (collider.sensor) {
            return undefined;
        }

        let character = collider.getComponent(BaseCharacter);
        return character;
    }

    /**
     * 播放动画
     * @param name 
     * @param spine 
     */
    public static playAnimationPromise(name: string, spine: sp.Skeleton) {
        let promise: Promise<void> = new Promise<void>((resolve, reject) => {
            spine.setAnimation(0, name, false);
            spine.setCompleteListener(() => {
                resolve();
            });
            spine.setInterruptListener(() => {
                reject();
            });
        });

        promise.then(
            (value) => {

            }, (error) => {
                console.log(error);
            }
        )

        return promise;
    }


    /**
     * 默认从怪物中选择一只进行攻击
     * @param enemySet 
     */
    public static selectEnemy(enemySet: Set<BaseCharacter>): BaseCharacter | null {
        let monsters = Array.from(enemySet.values());
        monsters = monsters.filter((item) => {
            return item.gameIng;
        });

        if (monsters.length <= 0) {
            return null;
        }

        return monsters[0];
    }

    /**
     * 计算子弹发射方向
     * @param target 目标节点
     * @param origin 出发节点
     */
    public static shootLinearVelocity(target: Node, origin: Node): math.Vec2 {
        let ePos = target.getWorldPosition();
        let mPos = origin.getWorldPosition();
        let v = v2(ePos.x - mPos.x, ePos.y - mPos.y);
        return v
    }
}